#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#




import wsgiref.handlers


from google.appengine.ext import webapp
from google.appengine.ext import db
import cgi
import time
import datetime
import logging

class TEntry(db.Model):
  building = db.StringProperty()
  room = db.StringProperty()
  tstamp = db.DateTimeProperty(auto_now_add=True)
  temp = db.IntegerProperty()

class MainHandler(webapp.RequestHandler):

  def get(self):
    b = cgi.escape(self.request.get('building'))
    t = cgi.escape(self.request.get('temp'))
    r = cgi.escape(self.request.get('room'))
    lang = cgi.escape(self.request.get('lang'))
    
    if t and b and r: 
      entry = TEntry(building=b, room=r, temp=int(t))
      entry.put()
    
    # todo: differentiate languages
    if lang:
      #self.response.out.write("<html><head><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/thankyou_k.html\"></head></html>")
      self.redirect('/thankyou_k.html')
    else:
      #self.response.out.write("<html><head><meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=/thankyou.html\"></head></html>")
      self.redirect('/thankyou.html')
    

class ViewHandler(webapp.RequestHandler):
  
  def get(self):
    startdate = cgi.escape(self.request.get('startdate'))
    stopdate = cgi.escape(self.request.get('stopdate'))
    
    if startdate:
      if startdate == '0':
        startdate = None
      else:
        sd = time.gmtime(float(startdate) / 1000.0)
        startdate = datetime.datetime(sd[0], sd[1], sd[2], sd[3], sd[4])
        logging.info('got startdate: ' + str(startdate) + '<br />')
    
    if stopdate:
      if stopdate == '0':
        stopdate = None
      else:
        sd = time.gmtime(float(stopdate) / 1000.0)
        stopdate = datetime.datetime(sd[0], sd[1], sd[2], sd[3], sd[4])
        logging.info('got stopdate: ' + str(stopdate))
    
    buildings = {}
    query = TEntry.all()
    
    # use datastore's filter capability
    if startdate and stopdate:
      query.filter('tstamp >', startdate).filter('tstamp <', stopdate)
    
    
    
    for entry in query:
      if not buildings.has_key(entry.building):
        buildings[entry.building] = 0
      buildings[entry.building] += int(entry.temp)
      logging.info('building: ' + entry.building + ' ' + str(int(entry.temp)))
      
    # write out as a single chunk of url data that Flash understands
    self.response.out.write('&'.join(map(lambda x: x[0] + '=' + str(x[1]), buildings.items())))
      
  
class DataHandler(webapp.RequestHandler):
  
  def get(self):
    for entry in TEntry.all():
      self.response.out.write(entry.building + ',' + entry.room + ',' + str(entry.temp) + ',' + str(entry.tstamp) + '\n')

class BlankHandler(webapp.RequestHandler):
  
  def get(self):
    self.redirect('/index.html')
    
def main():
  application = webapp.WSGIApplication([('/', BlankHandler),
                                        ('/entry', MainHandler),
                                        ('/view', ViewHandler),
                                        ('/data', DataHandler)], debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
